package com.banciyuan.bcywebview.biz.main.newdiscover;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.fragment.BaseContainerFragment;
import com.banciyuan.bcywebview.base.fragment.BasePullLoadFragment;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.exhibition.ExhibitionFragment;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.main.newdiscover.index.NewDiscoverFragment;
import com.banciyuan.bcywebview.biz.post.ScreenShots;
import com.banciyuan.bcywebview.biz.post.StartPostActivity;
import com.banciyuan.bcywebview.biz.search.SearchActivity;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2016/5/26.
 */
public class DiscoverFragment extends BasePullLoadFragment implements View.OnClickListener {
    public static final int TAG = 1;
    private ViewPager mPager;
    private MyAdapter mAdapter;
    private TabLayout tabLayout;
    private List<Fragment> mList = new ArrayList<>();
    private NewDiscoverFragment recommendFragment;
    private IllustDiscoverFragment illustFragment;
    private NovelDiscoverFragment novelFragment;
    private CosDiscoverFragment cosFragment;
    private ExhibitionFragment exhibitionFragment;
    private String[] tabs;

    private View post;
    private View login;
    private TextView mSearchHint;
    private List<TagDetail> hotSearchTags;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.discover_fragment, container, false);
        initArgs();
        getFragment();
        initUi(rootView);
        initAction();
        initHotTags();
        return rootView;
    }

    private void initHotTags() {
        List<BcyPair> paramsList = new ArrayList<>();
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + TagApi.getSearchTags();
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    String status = result.getString(HttpUtils.UPLOAD_STATUS);
                    if (status.equals("1")) {
                        Gson gson = new Gson();
                        hotSearchTags = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<TagDetail>>() {
                        }.getType());
                        processHotData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, onSucc, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(stringRequest);
    }

    private void processHotData() {
        if (hotSearchTags != null && !hotSearchTags.isEmpty()) {
            String hotTag = hotSearchTags.get(0).getTag_name();
            if (!TextUtils.isEmpty(hotTag))
                mSearchHint.setText(String.format(getString(R.string.search_hot_content_format), hotTag));
            else
                mSearchHint.setText(getString(R.string.search_your_interest_circle));
        } else {
            mSearchHint.setText(getString(R.string.search_your_interest_circle));
        }
    }

    @Override
    protected void initArgs() {
        tabs = new String[]{
                getString(R.string.hot),
                getString(R.string.draw),
                getString(R.string.write),
                getString(R.string.cos),
                getString(R.string.exhibition)};
    }

    @Override
    protected void initUi(View rootview) {

        post = rootview.findViewById(R.id.post_tv);
        login = rootview.findViewById(R.id.view_login);
        mPager = (ViewPager) rootview.findViewById(R.id.daily_pager);
        tabLayout = (TabLayout) rootview.findViewById(R.id.tablayout);
        mAdapter = new MyAdapter(getChildFragmentManager());
        mPager.setAdapter(mAdapter);
        mPager.setOffscreenPageLimit(5);
        tabLayout.setupWithViewPager(mPager);

        rootview.findViewById(R.id.search).setOnClickListener(this);
        mSearchHint = (TextView) rootview.findViewById(R.id.textView);
        post.setOnClickListener(this);
        login.setOnClickListener(this);

        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            post.setVisibility(View.VISIBLE);
            login.setVisibility(View.INVISIBLE);
        } else {
            post.setVisibility(View.INVISIBLE);
            login.setVisibility(View.VISIBLE);
        }
    }


    private void getFragment() {

        recommendFragment = new NewDiscoverFragment();

        illustFragment = new IllustDiscoverFragment();
        novelFragment = new NovelDiscoverFragment();
        cosFragment = new CosDiscoverFragment();
        exhibitionFragment = new ExhibitionFragment();

        mList.add(recommendFragment);
        mList.add(illustFragment);
        mList.add(novelFragment);
        mList.add(cosFragment);
        mList.add(exhibitionFragment);
    }

    @Override
    protected void initAction() {
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                switch (tab.getPosition()) {
                    case 1:
                        StatService.onEvent(getActivity(), EventConstants.DISCOVER_ILLUST, EventConstants.DISCOVER_ILLUST_EVENT);
                        break;
                    case 2:
                        StatService.onEvent(getActivity(), EventConstants.DISCOVER_WRITER, EventConstants.DISCOVER_WRITER_EVENT);
                        break;
                    case 3:
                        StatService.onEvent(getActivity(), EventConstants.DISCOVER_COS, EventConstants.DISCOVER_COS_EVENT);
                        break;
                    case 4:
                        StatService.onEvent(getActivity(), EventConstants.EXHIBITION, EventConstants.ENTER_CIRCLE_EVENT);
                        break;
                }
            }
        });
    }

    @Override
    public void selfUpdateData() {
        try {
            Fragment currentFragment = mAdapter.getItem(mPager.getCurrentItem());
            ((BaseContainerFragment) currentFragment).selfUpdateData();
        } catch (Exception e) {
        }
    }

    class MyAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabs[position];
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                gotoSearchActivity();
                break;
            case R.id.post_tv:
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        ScreenShots screenShots = new ScreenShots(getActivity());
                        screenShots.takeShot();
                    }
                });
                gotoUtil.gotoAct(getActivity(), StartPostActivity.class, "main");
                getActivity().overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                break;
            case R.id.view_login:
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                break;
            default:
                break;
        }
    }

    private void gotoSearchActivity() {
        Intent intent = new Intent(getActivity(), SearchActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, "all");
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, (Serializable) hotSearchTags);
        startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        exhibitionFragment.onActivityResult(requestCode, resultCode, data);
    }

}
